package net.zio.kamenriderzioaddon.network.message;

import net.minecraft.client.Minecraft;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.network.NetworkEvent;
import net.zio.kamenriderzioaddon.procedures.SetupAnimationsProcedure;
import net.zio.kamenriderzioaddon.network.IMessage;
import net.zio.kamenriderzioaddon.KamenRiderZioAddonMod;

import dev.kosmx.playerAnim.core.data.KeyframeAnimation;
import dev.kosmx.playerAnim.minecraftApi.PlayerAnimationRegistry;

import net.minecraft.resources.ResourceLocation;
import java.util.UUID;

/**
 * 动画消息
 *
 * @author QuanYunYi
 */
public class AnimationMessage implements IMessage {
    // 动画名称
    private final String animationName;
    // 玩家UUID
    private final UUID playerUUID;
    // 是否开始播放
    private final boolean start;

    /**
     * @param animationName 动画名称
     * @param playerUUID    玩家UUID
     * @param start         是否开始播放
     */
    public AnimationMessage(String animationName, UUID playerUUID, boolean start) {
        this.animationName = animationName;
        this.playerUUID = playerUUID;
        this.start = start;
    }

    /**
     * @param buffer 数据缓冲
     */
    public AnimationMessage(FriendlyByteBuf buffer) {
        this.animationName = buffer.readUtf(32767);
        this.playerUUID = buffer.readUUID();
        this.start = buffer.readBoolean();
    }

    /**
     * @param buffer 数据缓冲
     */
    @Override
    public void encode(FriendlyByteBuf buffer) {
        buffer.writeUtf(animationName);
        buffer.writeUUID(playerUUID);
        buffer.writeBoolean(start);
    }

    /**
     * @param context 网络上下文
     */
    @Override
    public void handle(NetworkEvent.Context context) {
        if (context.getDirection().getReceptionSide().isClient()) {
            context.enqueueWork(() -> {
                Minecraft mc = Minecraft.getInstance();
                if (mc.level == null) return;

                Player player = mc.level.getPlayerByUUID(playerUUID);
                if (player == null) {
                    KamenRiderZioAddonMod.LOGGER.warn("无法找到UUID为 {} 的玩家", playerUUID);
                    return;
                }

                // 直接播放动画
                playAnimationDirectly(player);
            });
        }
        context.setPacketHandled(true);
    }

    /**
     * 直接播放动画
     *
     * @param player 玩家
     */
    private void playAnimationDirectly(Player player) {
        ResourceLocation animId = new ResourceLocation("kamen_rider_zio_addon", animationName);
        KeyframeAnimation animation = PlayerAnimationRegistry.getAnimation(animId);

        if (animation == null) {
            KamenRiderZioAddonMod.LOGGER.error("动画未找到: {}", animId);
            return;
        }

        // 使用新的动画播放方法
        if (this.start) {
            SetupAnimationsProcedure.playAnimation(player, animationName, true);
        }
    }
}